package cn.edu.buu.news.service.impl;

import cn.edu.buu.news.entity.User;
import cn.edu.buu.news.entity.UserTaskNote;
import cn.edu.buu.news.exception.ExceptionInfoEnum;
import cn.edu.buu.news.exception.NewsException;
//import cn.edu.buu.news.mapper.AdminMapper;
import cn.edu.buu.news.mapper.UserMapper;
import cn.edu.buu.news.mapper.UserTaskNoteMapper;
import cn.edu.buu.news.service.UserService;
import cn.edu.buu.news.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void add(User admin) {userMapper.insert(admin);}

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserTaskNoteMapper userTaskNoteMapper;

    // 从配置文件获取头像存储路径
    @Value("${upload.avatar.path}")
    private String avatarPath;

    // 头像访问基础URL（如：http://localhost:8080/avatars/）
    @Value("${upload.avatar.base-url}")


    private String avatarBaseUrl;



    @Override
    public void logout(Long id) {
        Set keys = redisTemplate.keys("news:admin:" + id + ":*");
        redisTemplate.delete(keys);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Result findAdmin(String userName, String password) {


        User loginAdmin=this.userMapper.selectAdmin(userName,password);


        if(loginAdmin==null){//登录失败，用户名密码错误
            throw new NewsException(ExceptionInfoEnum.LOGINFAIL.getCode(),ExceptionInfoEnum.LOGINFAIL.getErrorMessage());
        }
        //登录成功，检查redis中是否已经有该用户的登录信息，有则删掉，无则添加
        Set keys =redisTemplate.keys("news:admin:"+loginAdmin.getId()+":*");
        if (keys.size()>0){//redis中有此用户登录信息
            redisTemplate.delete(keys);//把之前登录的用户踢走了
        }
        //产生token令牌，唯一,UUID
        String token = UUID.randomUUID().toString();

        //存入redis
        redisTemplate.opsForValue().set("news:admin:"+loginAdmin.getId()+":"+token,
                loginAdmin,30, TimeUnit.MINUTES);//ttl:time to live

        //Map，响应给客户端
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("loginAdmin",loginAdmin);

        return Result.success(map);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean updateUserInfo(User user) {
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.updateById(user) > 0;
    }

    @Override
    public String uploadAvatar(MultipartFile file) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return null;
        }

        // 确保上传目录存在
        File dir = new File(avatarPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        // 保存文件
        File dest = new File(avatarPath + File.separator + fileName);
        file.transferTo(dest);

        // 返回可访问的URL
        return avatarBaseUrl + fileName;
    }

    @Override
    public boolean updateAvatarUrl(Long userId, String avatarUrl) {
        User user = new User();
        user.setId(userId);
        user.setHeadPic(avatarUrl);
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.updateById(user) > 0;
    }



    @Override
    public boolean saveNote(UserTaskNote note) {
        // 检查是否已存在该任务的笔记
        UserTaskNote existingNote = userTaskNoteMapper.selectByUserTaskId(note.getUserTaskId());

        if (existingNote != null) {
            // 更新已有笔记
            existingNote.setNotes(note.getNotes());
            existingNote.setUpdateTime(LocalDateTime.now());
            return userTaskNoteMapper.updateById(existingNote) > 0;
        } else {
            // 新增笔记
            note.setCreateTime(LocalDateTime.now());
            note.setUpdateTime(LocalDateTime.now());
            return userTaskNoteMapper.insert(note) > 0;
        }
    }


}
